﻿#include "cxiverticalheaderview.h"
#include "cxiadvancedview.h"

#include <QPainter>
#include <QPaintEvent>

CxiVerticalHeaderView::CxiVerticalHeaderView(QWidget* parent)
	: QHeaderView(Qt::Vertical, parent), m_view(nullptr)
{
	setSectionsClickable(false);
	setSectionsMovable(false);
	setDefaultSectionSize(24);
	setMinimumWidth(40);
	// 可选：固定宽度，去掉则允许宽度变化
	setFixedWidth(40);
}

void CxiVerticalHeaderView::paintEvent(QPaintEvent *event)
{
 	QPainter painter(this);
	painter.save();

	// 背景区域
	painter.fillRect(event->rect(), QColor(245, 245, 245));
	painter.setPen(Qt::gray);

	if (!m_view) {
		// 无 view 时退化为父类行为
		QHeaderView::paintEvent(event);
		painter.restore();
		return;
	}

	// 如果处于分组/树模式，暂时保留接口（不绘制表格编号）
	if (m_view->isGroupingEnabled()) {
		QHeaderView::paintEvent(event);
		painter.restore();
		return;
	}

	// 表格模式：按 model 的逻辑行绘制行号（从1开始）
	QAbstractItemModel *m = m_view->model();
	if (!m) { painter.restore(); return; }

	QModelIndex root = m_view->rootIndex();
	const int rowCount = m->rowCount(root);
	for (int logicalRow = 0; logicalRow < rowCount; ++logicalRow) {
		// 以第0列 index 作为参考绘制位置
		QModelIndex idx = m->index(logicalRow, 0, root);
		if (!idx.isValid())
			continue;
		QRect vr = m_view->visualRect(idx); // 相对于 viewport 的 rect
		if (vr.isEmpty())
			continue;

		QRect sectionRect(0, vr.top(), width(), vr.height());
		if (!event->region().intersects(sectionRect))
			continue;

		// 绘制背景与边框
		painter.fillRect(sectionRect, QColor(245, 245, 245));
		painter.setPen(Qt::gray);
		painter.drawRect(sectionRect.adjusted(0, 0, -1, -1));

		// 绘制行号（logicalRow + 1）
		QString text = QString::number(logicalRow + 1);
		painter.setPen(Qt::black);
		painter.drawText(sectionRect, Qt::AlignCenter, text);
	}

	painter.restore();
}